package com.sumer.psychology.microblog.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.comment.application.command.CommentApplicationService;
import com.sumer.psychology.comment.application.command.DeleteCommentsCommand;
import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import com.sumer.psychology.microblog.infrastructure.persistence.mongo.MongoMicroBlogRepository;

/**
 * 微博删除监听
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/2
 * Time: 15:04
 */
public class MicroBlogDeletedEventListener extends ExchangeListener {
    private CommentApplicationService commentApplicationService;
    private MongoMicroBlogRepository mongoMicroBlogRepository;

    public MicroBlogDeletedEventListener(
            CommentApplicationService commentApplicationService,
            MongoMicroBlogRepository mongoMicroBlogRepository) {
        this.commentApplicationService = commentApplicationService;
        this.mongoMicroBlogRepository = mongoMicroBlogRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        NotificationReader reader = new NotificationReader(aTextMessage);
        String hostId = reader.eventStringValue("microBlogId.identity");

        commentApplicationService().delete(
                new DeleteCommentsCommand(hostId));

        mongoMicroBlogRepository().removeOne(hostId);
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.microblog.domain.model.MicroBlogDeletedEvent"};
    }

    private CommentApplicationService commentApplicationService() {
        return commentApplicationService;
    }

    private MongoMicroBlogRepository mongoMicroBlogRepository() {
        return mongoMicroBlogRepository;
    }
}
